package com.hmdp.redis;

import cn.hutool.core.lang.UUID;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock{

    private StringRedisTemplate stringRedisTemplate;
    private String  name;

    public SimpleRedisLock(StringRedisTemplate stringRedisTemplate, String name) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.name = name;
    }

    private static  final  String KEY_PREFIX="lock";
    private static  final  String ID_PREFIX= UUID.randomUUID().toString(true)+"-";
    @Override
    public boolean tryLock(long timeoutSec) {
        //使用线程ID+UUID的方式
        String threadId = Thread.currentThread().getId()+ID_PREFIX;
        //获取锁
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, threadId, timeoutSec, TimeUnit.MINUTES);
        return Boolean.TRUE.equals(success);
    }

    @Override
    public void unlock() {
        //判断是不是当前的线程ID在进行释放
        String threadId = Thread.currentThread().getId()+ID_PREFIX;
        String lock = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
        if (threadId.equals(lock) ) {
        stringRedisTemplate.delete(KEY_PREFIX + name);

        }
    }
}
